package cn.wolfcode.trip.admin.shiro;

import cn.wolfcode.trip.base.domain.Employee;
import cn.wolfcode.trip.base.mapper.EmployeeMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author by mycp
 * @Classname MyRealm
 * @Description TODO 自定义shiro的数据源, 自提供认证信息/授权信息对象
 * @Date 2018/10/23 23:20
 */
public class MyRealm extends AuthorizingRealm {
    // 注入mapper对象
    @Autowired
    private EmployeeMapper employeeMapper;
    // 用户主体subject的认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        // 获取令牌中的用户名
        String username = (String) token.getPrincipal();
        // 根据用户名查询员工信息
        Employee employee = employeeMapper.selectEmployeeByUsername(username);
        if (employee != null){
            // 把整个员工对象传入当做subject的身份信息, 密码, 密码加密的盐, 当前realm的名字
            return new SimpleAuthenticationInfo(employee, employee.getPassword(),
                    ByteSource.Util.bytes(employee.getName()) ,getName());
        }
        return null;
    }
    // 授权当前subject
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取认证信息中的用户
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        Long id = employee.getId();
        // 授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (employee.isAdmin()){
            // 设置角色为admin
            info.addRole("ADMIN");
            // 如果只admin,则直接授权所有的权限
            info.addStringPermission("*:*");
        } else {
            // 查询的所用角色编号信息
            List<String> rolesSn = employeeMapper.getAllRolesSnByUserId(id);
            // 查询用户的权限
            List<String> permissions = employeeMapper.getAllPermissionExpressionByUserId(id);
            // 将用户的角色和权限封装到授权对象中

            info.addRoles(rolesSn);
            info.addStringPermissions(permissions);
        }
        return info;
    }
}
